define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'kuerp/sale_goals/index' + location.search,
                    add_url: 'kuerp/sale_goals/add',
                    edit_url: 'kuerp/sale_goals/edit',
                    del_url: 'kuerp/sale_goals/del',
                    multi_url: 'kuerp/sale_goals/multi',
                    import_url: 'kuerp/sale_goals/import',
                    table: 'kuerp_sale_goals',
                }
            });

            var table = $("#table");
            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                fixedColumns: true,
                fixedRightNumber: 1,
                columns: [
                    [
                        {checkbox: true},
                        // {field: 'id', title: __('Id'), operate: false},
                        {field: 'name', title: __('Name'), operate: 'LIKE'},
                        {field: 'model_class', title: __('Model_class'), searchList:Config.modelList, formatter: Table.api.formatter.normal},
                        {field: 'years', title: __('Years'), operate: 'LIKE', searchList:Config.yearlist, table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        {field: 'status', title: __('Status'), searchList: {"1":__('Status 1'),"0":__('Status 0')}, formatter: Table.api.formatter.status},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, 
                            buttons: [
                                {
                                    name: 'edit',
                                    text: __('编辑'),
                                    classname: 'btn btn-xs btn-success  btn-dialog',
                                    icon: 'fa fa-pencil',
                                    url: function (row, column) { //row 表格接收到的数据
                                        return "kuerp/sale_goals/edit/ids/" + row.id; //弹窗的对应后台控制器方法 这里是默认index方法 加id参数
                                    },
                                    extend: 'data-area=\'["80%","80%"]\'',
                                    refresh: false
                                },
                                {
                                    name: 'editdetail',
                                    text: __('目标设置'),
                                    classname: 'btn btn-xs btn-warning btn-dialog',
                                    icon: 'fa fa-pie-chart',
                                    url: function (row, column) { //row 表格接收到的数据
                                        return "kuerp/sale_goals/editdetail/ids/" + row.id; //弹窗的对应后台控制器方法 这里是默认index方法 加id参数
                                    },
                                    extend: 'data-area=\'["100%","90%"]\'',
                                    refresh: true
                                }
                            ],
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
            
        },
        recyclebin: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    'dragsort_url': ''
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: 'kuerp/sale_goals/recyclebin' + location.search,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'name', title: __('Name'), align: 'left'},
                        {
                            field: 'deletetime',
                            title: __('Deletetime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'operate',
                            width: '140px',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'Restore',
                                    text: __('Restore'),
                                    classname: 'btn btn-xs btn-info btn-ajax btn-restoreit',
                                    icon: 'fa fa-rotate-left',
                                    url: 'kuerp/sale_goals/restore',
                                    refresh: true
                                },
                                {
                                    name: 'Destroy',
                                    text: __('Destroy'),
                                    classname: 'btn btn-xs btn-danger btn-ajax btn-destroyit',
                                    icon: 'fa fa-times',
                                    url: 'kuerp/sale_goals/destroy',
                                    refresh: true
                                }
                            ],
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },

        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        editdetail: function () {
            var table = $("#table");
            
            const q = {};
            location.search.replace(/([^?&=]+)=([^&]+)/g,function(_,k,v){q[k]=v});
            let filter = {}
            var id = Config.id
            var year = Config.year
            filter.id = id
            filter.year = year
            filter.department_id = Config.departmentList[0].id
            require(['jstree'], function () {
                $('#departmenttree').on("changed.jstree", function (e, data) {
                    var department_id = data.selected.join(",")
                    if (department_id.indexOf('admin') > -1){
                        var admin_id = department_id.replace('admin_', '')
                        var t = '2_' + admin_id+'_'+year
                        if (allDataList[t]) {
                            rows = [allDataList[t]]
                            // 刷新表格
                        table.bootstrapTable('load', rows);
                        } else {
                            $.ajax({
                                type:'get', 
                                url:'kuerp/sale_goals/detail_list', 
                                data:{id, year, admin_id, department_id:filter.department_id}, 
                                success:function (res) {
                                    rows = res.data
                                    allDataList[t] = res.data[0] ?? []
                                    // 刷新表格
                                    table.bootstrapTable('load', rows);
                                }
                            })
                        }
                        
                        
                    } else {
                        filter.department_id = department_id
                        table.bootstrapTable('refresh');
                    }
                    
                    return false;
                });
                $('#departmenttree').jstree({
                    "types": {
                        "channel": {
                            "icon": false,
                        },
                        "list": {
                            "icon": false,
                        },
                        "link": {
                            "icon": false,
                        },
                        "disabled": {
                            "check_node": false,
                            "uncheck_node": false
                        }
                    },
                    'plugins': ["types", "themes"],
                    "core": {
                        "multiple": false,
                        'check_callback': true,
                        "data": Config.departmentList,
                        "themes": {
                            "dots": false,
                        }
                    }
                }).on('ready.jstree', function() {
                    $('#departmenttree').jstree(true).select_node(Config.departmentList[0].id);
                });
                
            });
            let departments = Config.departmentnames
            let adminList = Config.adminList
            let allDataList = {}
            // 初始化表格
            table.bootstrapTable({
                url: 'kuerp/sale_goals/detail_list',
                queryParams: function(params) {
                    return Object.assign(params, filter);
                },
                // pk: 'id',
                sortName: 'department_id',
                pagination:false,
                fixedColumns: true,
                fixedNumber: 1,
                columns: [
                    [
                        {field: 'name', title: __('考核对象'), operate: false, formatter:function(value, row, index) {
                            var name = row.type == 1 ? departments[row.department_id] : adminList[row.admin_id]
                            return '<div class="flex-between"><div>'+name+'</div><i class="fa fa-pencil editRow" data-index="'+index+'"></i></div>'
                        },width:150},
                        {field: 'yeartarget', title: __('全年'), operate: false, formatter:function(value, row, index) {
                            return Number(row.month_1) + Number(row.month_2) + Number(row.month_3)+Number(row.month_4) + Number(row.month_5) + Number(row.month_6)+Number(row.month_7) + Number(row.month_8) + Number(row.month_9)+Number(row.month_10) + Number(row.month_11) + Number(row.month_12)
                        },width:120},
                        {field: 'one', title: __('第一季度'), operate: false, formatter:function(value, row, index) {
                            return Number(row.month_1) + Number(row.month_2) + Number(row.month_3)
                        },width:120},
                        {field: 'month_1', title: '<div class="flex-between"><div>1月</div><i class="fa fa-pencil editCol" data-field="month_1"></i></div>', operate: false, formatter:function(value, row, index) {
                            return celltemplate(index, 'month_1', row.month_1);
                        },width:120},
                        {field: 'month_2', title: '<div class="flex-between"><div>2月</div><i class="fa fa-pencil editCol" data-field="month_2"></i></div>', operate: false, formatter:function(value, row, index) {
                            return celltemplate(index, 'month_2', row.month_2);
                        },width:120},
                        {field: 'month_3', title: '<div class="flex-between"><div>3月</div><i class="fa fa-pencil editCol" data-field="month_3"></i></div>', operate: false, formatter:function(value, row, index) {
                            return celltemplate(index, 'month_3', row.month_3);
                        },width:120},
                        {field: 'two', title: __('第二季度'), operate: false, formatter:function(value, row, index) {
                            return Number(row.month_4) + Number(row.month_5) + Number(row.month_6)
                        },width:120},
                        {field: 'month_4', title: '<div class="flex-between"><div>4月</div><i class="fa fa-pencil editCol" data-field="month_4"></i></div>', operate: false, formatter:function(value, row, index) {
                            return celltemplate(index, 'month_4', row.month_4);
                        },width:120},
                        {field: 'month_5', title: '<div class="flex-between"><div>5月</div><i class="fa fa-pencil editCol" data-field="month_5"></i></div>', operate: false, formatter:function(value, row, index) {
                            return celltemplate(index, 'month_5', row.month_5);
                        },width:120},
                        {field: 'month_6', title: '<div class="flex-between"><div>6月</div><i class="fa fa-pencil editCol" data-field="month_6"></i></div>', operate: false, formatter:function(value, row, index) {
                            return celltemplate(index, 'month_6', row.month_6);
                        },width:120},
                        {field: 'three', title: __('第三季度'), operate: false, formatter:function(value, row, index) {
                            return Number(row.month_7) + Number(row.month_8) + Number(row.month_9)
                        },width:120},
                        {field: 'month_7', title: '<div class="flex-between"><div>7月</div><i class="fa fa-pencil editCol" data-field="month_7"></i></div>', operate: false, formatter:function(value, row, index) {
                            return celltemplate(index, 'month_7', row.month_7);
                        },width:120},
                        {field: 'month_8', title: '<div class="flex-between"><div>8月</div><i class="fa fa-pencil editCol" data-field="month_8"></i></div>', operate: false, formatter:function(value, row, index) {
                            return celltemplate(index, 'month_8', row.month_8);
                        },width:120},
                        {field: 'month_9', title: '<div class="flex-between"><div>9月</div><i class="fa fa-pencil editCol" data-field="month_9"></i></div>', operate: false, formatter:function(value, row, index) {
                            return celltemplate(index, 'month_9', row.month_9);
                        },width:120},
                        {field: 'four', title: __('第四季度'), operate: false, formatter:function(value, row, index) {
                            return Number(row.month_10) + Number(row.month_11) + Number(row.month_12)
                        },width:120},
                        {field: 'month_10', title: '<div class="flex-between"><div>10月</div><i class="fa fa-pencil editCol" data-field="month_10"></i></div>', operate: false, formatter:function(value, row, index) {
                            return celltemplate(index, 'month_10', row.month_10);
                        },width:120},
                        {field: 'month_11', title: '<div class="flex-between"><div>11月</div><i class="fa fa-pencil editCol" data-field="month_11"></i></div>', operate: false, formatter:function(value, row, index) {
                            return celltemplate(index, 'month_11', row.month_11);
                        },width:120},
                        {field: 'month_12', title: '<div class="flex-between"><div>12月</div><i class="fa fa-pencil editCol" data-field="month_12"></i></div>', operate: false, formatter:function(value, row, index) {
                            return celltemplate(index, 'month_12', row.month_12);
                        },width:120},
                    ]
                ],
                onLoadSuccess: function (data) {
                    var reload = false
                    for (var i = 0; i < data.data.length; i++) {
                        var item = data.data[i]
                        var t = item.type+'_'+(item.type == 1 ? item.department_id : item.admin_id)+'_'+item.year
                        if (!allDataList[t]){
                            allDataList[t] = item
                        } else {
                            reload = true
                            data.data[i] = allDataList[t]
                        }
                    }
                    if (reload) table.bootstrapTable('load', data.data);
                 }
            });
            $('#s-year').change(function(e){
                filter.year = $(this).val()
                table.bootstrapTable('refresh')
            })
            // 监听 radio 按钮的变化
            $(document).on('change', 'input[name="editType"]', function() {
                console.log('value', $(this).val())
                if ($(this).val() === 'each') {
                    // 如果选择了 "each"，则使 eachValue 必填且大于 0
                    $('input[name="eachValue"]').attr('data-rule', 'required;range(0~)');
                    $('input[name="totalValue"]').removeAttr('data-rule');
                } else if ($(this).val() === 'total') {
                    // 如果选择了 "total"，则使 totalValue 必填且大于 0
                    $('input[name="eachValue"]').removeAttr('data-rule');
                    $('input[name="totalValue"]').attr('data-rule', 'required;range(0~)');
                }
            });

            $(document).on('click', '.editRow', function(e){
                var index = $(this).data('index')
                layer.open({
                    type: 1,
                    title:'批量编辑行',
                    area: ['600px', '300px'],
                    content: $('#editRow').html(),//这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
                    btn:['确认', '取消'],
                    yes: function(layerindex, layero){
                        Form.events.validator($('#editRow-form'))
                        var type = $('[name="editType"]:checked').val();
                        var value = 0;
                        //获取当前页面条数
                        var rows = table.bootstrapTable('getData')
                        if (type == 'each') {
                            value = $('[name="eachValue"]').val()
                        }else{
                            value = $('[name="totalValue"]').val()
                            value = Number(value) / 12
                        }
                        if (isNaN(value) || value == '') {
                            layer.msg('请输入数字')
                            return false
                        }
                        if (value < 0) {
                            layer.msg('请输入大于0的数字')
                            return false
                        }
                        if (rows[index]) {
                            var t = rows[index].type+'_'+(rows[index].type == 1 ? rows[index].department_id : rows[index].admin_id)+'_'+rows[index].year
                            for (var i = 1; i <= 12; i++) {
                                var field = 'month_' + i
                                rows[index][field] = value
                                allDataList[t][field] = value
                            }
                        }
                        // 刷新表格
                        table.bootstrapTable('updateRow', {
                            index: index,
                            row: rows[index]
                        });
                        // table.bootstrapTable('load', rows);
                        layer.close(layerindex); //如果设定了yes回调，需进行手工关闭
                    },
                    cancel: function(layerindex, layero){ 
                        layer.close(layerindex)
                        return false; 
                    }
                  });
            })
            $(document).on('click', '.editCol', function(e){
                var field = $(this).data('field')
                layer.open({
                    type: 1,
                    title:'批量编辑列',
                    area: ['600px', '300px'],
                    content: $('#editCol').html(),  //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
                    btn:['确认', '取消'],
                    yes: function(layerindex, layero){
                        Form.events.validator($('#editCol-form'))
                        var type = $('[name="editType"]:checked').val();
                        var value = 0;
                        //获取当前页面条数
                        var rows = table.bootstrapTable('getData')
                        if (type == 'each') {
                            value = $('[name="eachValue"]').val()
                        }else{
                            value = $('[name="totalValue"]').val()
                            value = Number(value) / (rows.length - 1)
                        }
                        if (isNaN(value) || value == '') {
                            layer.msg('请输入数字')
                            return false
                        }
                        if (value < 0) {
                            layer.msg('请输入大于0的数字')
                            return false
                        }
                        
                        // 更新每一行的数据
                        rows.forEach(function(row, index) {
                            if (index > 0){
                                row[field] = value;
                                var t = row.type+'_'+(row.type == 1 ? row.department_id : row.admin_id)+'_'+row.year
                                if (allDataList[t]) {
                                    allDataList[t][field] = value
                                }
                            }
                        });
                        // 刷新表格
                        table.bootstrapTable('load', rows);
                        layer.close(layerindex); //如果设定了yes回调，需进行手工关闭
                    },
                    cancel: function(layerindex, layero){ 
                        layer.close(layerindex)
                        return false; 
                    }
                  });
            })
            $(document).on('click', '.editable-cell-container .pencil-col', function() {
                var $icon = $(this); // 当前点击的编辑图标
                var $cell = $icon.prev(); // 获取前一个兄弟元素，即包含文本的 .editable-cell
                var field = $cell.data('field');
                var index = $cell.data('index');
                var value = $cell.text();

                // 创建一个输入框并填充当前值
                var input = $('<input type="number" class="form-control" min="0" style="height:30px"/>').val(value);

                // 替换单元格内容为输入框
                $cell.html(input);
                $icon.css('display', 'none')

                // 聚焦到输入框
                input.focus();

                // 失去焦点时保存修改
                input.on('blur', function() {
                    var newValue = input.val();
                    saveCellValue(index, field, newValue);
                    $cell.text(newValue);
                });

                // 按下回车键时保存修改
                input.on('keypress', function(e) {
                    if (e.which === 13) { // 回车键的键码是13
                        var newValue = input.val();
                        saveCellValue(index, field, newValue);
                        $cell.text(newValue);
                        input.blur(); // 隐藏输入框
                    }
                });
            });
            function celltemplate(index,field, value) {
                return `<div class="editable-cell-container" data-field="${field}" data-index="${index}">
                                        <div class="editable-cell" data-field="${field}" data-index="${index}">${value}</div>
                                        <i class="fa fa-pencil pencil-col" data-field="${field}"></i>
                                    </div>`;
            }
            function saveCellValue(index, field, newValue) {
                var data = table.bootstrapTable('getData');
                var row = data[index];
                row[field] = newValue;
                var t = row.type+'_'+(row.type == 1 ? row.department_id : row.admin_id)+'_'+row.year
                allDataList[t][field] = newValue

                // 更新表格数据
                table.bootstrapTable('updateRow', {
                    index: index,
                    row: row
                });

                // 这里可以添加额外的逻辑，比如发送请求到服务器保存数据
            }
            $(document).on('click', '#submit',function(){
                var data = Object.values(allDataList)
                var params = {
                    data
                }
                console.log('params', params);
                $.ajax({
                    type: 'POST',
                    url: 'kuerp/sale_goals/editdetail/ids/'+id,
                    data: params,
                    success: function (data) {
                        if (data.code == 1) {
                            layer.msg(data.msg)
                            setTimeout(function(){
                                allDataList = {}
                                Fast.api.close()
                            },1000)
                        }else{}
                    }
                })
            })
            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        api: {
            bindevent: function () {

                Form.api.bindevent($("form[role=form]"), function (data, ret){
                    if (ret.code == 1 && ret.data.need_url) {
                        Fast.api.close();
                        top.Fast.api.open('kuerp/sale_goals/editdetail/ids/'+ret.data.id, '目标值配置',{
                            area: [
                                '90%',
                                '80%'
                            ],
                        });
                        return false;
                    }
                });
            }
        }
    };
    return Controller;
});
